import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:get/get.dart';
import 'package:openim/pages/chat/group_setup/group_setup_logic.dart';
import 'package:openim_common/openim_common.dart';
import 'package:image_gallery_saver_plus/image_gallery_saver_plus.dart';

class GroupQrcodeLogic extends GetxController {
  final groupSetupLogic = Get.find<GroupSetupLogic>();
  final GlobalKey qrKey = GlobalKey();

  String buildQRContent() {
    // 使用与深度链接相同的自定义schema格式
    final groupId = groupSetupLogic.groupInfo.value.groupID;
    final inviterUserId = OpenIM.iMManager.userID;
  
    
    // 构建参数
    final params = <String, String>{
      'groupId': groupId,
    };
    
    if (inviterUserId != null && inviterUserId.isNotEmpty) {
      params['inviter'] = inviterUserId;
    }
    
    // 构建查询字符串
    final queryString = params.entries
        .map((e) => '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}')
        .join('&');
    
    // 返回自定义schema格式的链接
    return 'paxiy://group/invite?$queryString';
  }

  // 获取过期时间文本
  String getExpirationText() {
    // final now = DateTime.now();
    // final expirationDate = now.add(Duration(days: 7)); // 假设7天后过期
    // final formattedDate = '${expirationDate.month}月${expirationDate.day}日';
    // return '该二维码7天内(${formattedDate})有效，重新进入将更新';
    return "";
  }

  // 保存二维码到本地 - 使用已经生成的二维码
  Future<void> saveQRCodeToLocal() async {
    try {
      // 请求存储权限
      Permissions.storage(() async {
        try {
          // 获取已经渲染的二维码组件
          RenderRepaintBoundary? boundary = qrKey.currentContext?.findRenderObject() as RenderRepaintBoundary?;
          
          if (boundary != null) {
            // 捕获已显示的二维码图像
            ui.Image image = await boundary.toImage(pixelRatio: 3.0);
            ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
            
            if (byteData != null) {
              Uint8List uint8List = byteData.buffer.asUint8List();
              
              // 保存到相册ImageGallerySaverPlus
              final result = await ImageGallerySaverPlus.saveImage(
                uint8List,
                name: '群二维码_${groupSetupLogic.groupInfo.value.groupName}_${DateTime.now().millisecondsSinceEpoch}',
              );
              
              if (result != null) {
                IMViews.showToast('二维码已保存到相册');
              } else {
                IMViews.showToast('保存失败');
              }
            }
          } else {
            IMViews.showToast('无法获取二维码，请稍后重试');
          }
        } catch (e) {
          print('保存二维码失败: $e');
          IMViews.showToast('保存失败: $e');
        }
      });
    } catch (e) {
      print('保存二维码失败: $e');
      IMViews.showToast('保存失败');
    }
  }
}
